package com.gismore.demo.db.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gismore.demo.common.constants.FConst;
import com.gismore.demo.db.domain.SecUser;
import com.gismore.demo.db.mapper.SecUserMapper;
import com.gismore.demo.db.service.ISecUserService;
import com.gismore.demo.security.tooken.JwtAccessTokenProcessor;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Properties;

/**
 * <p>
 *   服务实现类
 * </p>
 *
 * @author lei
 * @since 2017-05-25
 */
@Service
public class SecUserServiceImpl extends ServiceImpl<SecUserMapper, SecUser> implements ISecUserService {
	@Autowired
	private SecUserMapper secUserMapper;


	@Override
	public Boolean verify(String accessToken){
		return findByToken(accessToken) != null;
	}

	@Override
	public SecUser findByToken(String accessToken) {
		Properties prop = JwtAccessTokenProcessor.parse(accessToken);
		String username = prop.getProperty(FConst.PARAMS_USERNAME);
		String password = prop.getProperty(FConst.PARAMS_PASSWORD);
		if(ObjectUtils.allNotNull(username,password)){
			SecUser secUser = secUserMapper.findByUasernameAndPassword(username,password);
			return secUser;
		}
		return null;
	}
	@Override
	public SecUser findByUser(String username, String password) throws Exception{
		return secUserMapper.findByUasernameAndPassword(username,password);
	}
	@Override
	public String generateToken(SecUser secUser){
		Map<String, Object> subject = Maps.newHashMapWithExpectedSize(2);
		subject.put(FConst.PARAMS_USERNAME,secUser.getUsername());
		subject.put(FConst.PARAMS_PASSWORD,secUser.getPassword());
		return JwtAccessTokenProcessor.createJWT(subject);
	}
}
